import React from 'react';
import TableTh from './tableTh/TableTh';
import TableTr from './tableTr/TableTr';
import styles from './table.scss';
import utils from '../../commons/utils';
// import Tween from '../../commons/tween';

function Tbody(props) {
  const trList = props.tableDatas.map((data, idx) => <TableTr key={idx} datas={data} />);
  return (
    <tbody>
      {trList}
    </tbody>
  );
}

Tbody.propTypes = {
  tableDatas: React.PropTypes.array.isRequired,
};

class Table extends React.PureComponent {
  static formatForTable(array) {
    const temp = array.map(({ seq, nums }, idx) => {
      let d;
      if (idx > 0) {
        d = utils.findRep(nums, array[idx - 1].nums).length;
      }
      return {
        seq,
        nums,
        three: nums.slice(0, 3),
        d,
        odd: nums.filter(n => (n % 2 === 1)).length,
      };
    });
    return temp.reverse();
  }

  constructor(props) {
    super(props);
    this.displayName = 'Table';

    this.state = {
      scrollTop: 0,
    };
  }

  componentDidUpdate() {
    // const wrapStyle = window.getComputedStyle(this.tableWrap);
    // const goalTop = (this.table.clientHeight +
    //   parseInt(wrapStyle.paddingBottom, 10) + parseInt(wrapStyle.paddingTop, 10))
    //   - document.body.clientHeight;
    // this.tableWrap.scrollTop = goalTop;
    // const wrapStyle = window.getComputedStyle(this.tableWrap);
    // const goalTop = (this.table.clientHeight +
    //   parseInt(wrapStyle.paddingBottom, 10) + parseInt(wrapStyle.paddingTop, 10))
    //   - document.body.clientHeight;
    // const scroll = () => {
    //   let start = 0;
    //   const during = 500;
    //   const run = () => {
    //     start += 1;
    //     const currentTop = this.tableWrap.scrollTop;
    //     const top = Tween.Cubic.easeOut(start, currentTop, goalTop - currentTop, during);
    //     this.tableWrap.scrollTop = top;
    //     if (this.tableWrap.scrollTop < goalTop && start < during) {
    //       this.animationId = requestAnimationFrame(run.bind(this));
    //     }
    //   };
    //   run();
    // };
    // scroll();
    //
  }

  componentsWillUnmont() {
    console.error('componentsWillUnmont');
    this.animationId = null;
  }

  render() {
    const datas = Table.formatForTable(this.props.datas);
    return (
      <div className={styles.wrap} ref={(o) => { this.tableWrap = o; }}>
        <table className={styles.mainTable} ref={(o) => { this.table = o; }}>
          <TableTh />
          <Tbody tableDatas={datas} />
        </table>
      </div>
    );
  }
}

Table.propTypes = {
  datas: React.PropTypes.array.isRequired,
};
export default Table;
